package com.c.config;

import com.c.securityservice.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author wangxiangli
 * @create 2022-12-23-17:07
 */
@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService myUserDetailsService;
    @Autowired
    private MyAuthenctiationSuccessHandler myAuthenctiationSuccessHandler;
    @Autowired
    private MyAuthenctiationFailureHandler myAuthenctiationFailureHandler;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     auth.userDetailsService(myUserDetailsService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login2.html").permitAll();
        //http.exceptionHandling().accessDeniedPage("/403.html");
       http.headers().frameOptions().sameOrigin();//inframe嵌入页面访问
        http.rememberMe();
        http.formLogin() //自定义自己编写的登录页面
            .loginPage("/login2.html")  //登录页面设置
            .loginProcessingUrl("/user/login") //登录访问设置
            .defaultSuccessUrl("/pages/main.html").permitAll()  //登录成功之后，跳转路径
            .failureForwardUrl("/login2.html")
             .successHandler(myAuthenctiationSuccessHandler)
             .failureHandler(myAuthenctiationFailureHandler)
            .and().authorizeRequests()
                  .antMatchers("/login2.html","/test/hello","/user/index","/banneradmin/**","/css/**","/img/**","/js/**","/plugins/**").permitAll() //设置哪些路径可以直接访问不需要认证
                  .antMatchers("/test/index").hasAnyAuthority("USER_ADD")
                  .antMatchers("/pages/**").access("isAuthenticated()")
            .anyRequest().authenticated()//除以上之外都需要认证
            .and().csrf().disable();//关闭csrf保护
    }
}
